import 'package:flutter/material.dart';
import 'package:get/get.dart';
// import 'package:music_app/api/dio_client.dart';
import 'package:music_app/models/api_response.dart';
import 'package:music_app/models/user.dart';

class LoginView extends StatefulWidget {
  const LoginView({super.key});

  @override
  State<LoginView> createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  final _formKey = GlobalKey<FormState>();
  final _phoneController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isLoading = false;
  // 模拟登录
  Future<Map<String, dynamic>> mockLoginRequest({
    required String phone,
    required String password,
  }) async {
    // 模拟 0.5 秒的网络延迟
    await Future.delayed(const Duration(milliseconds: 500));
    // 模拟成功响应
    if (phone == '12345678' && password == '12345678') {
      return {
        "code": 200,
        "message": "登录成功",
        "data": {
          "nickname": "张三",
          "id": 1001,
        }
      };
    } else {
      return {
        "code": 401,
        "message": "账号或密码错误",
      };
    }
  }

  // 点击登录
  Future<void> _login() async {
    if (!_formKey.currentState!.validate()) return;
    setState(() => _isLoading = true);
    try {
      // 网易云音乐和谐了这个接口
      // final response = await DioUtil().post('/login/cellphone', data: {
      //   'phone': _phoneController.text.trim(),
      //   'password': _passwordController.text.trim(),
      // });
      final response = await mockLoginRequest(
        phone: _phoneController.text.trim(),
        password: _passwordController.text.trim(),
      );
      final result = ApiResponse<User>.fromJson(
        response,
        (json) => User.fromJson(json),
      );
      if (result.code == 200) {
        Get.snackbar(
          '登录成功',
          '欢迎回来！',
          snackPosition: SnackPosition.TOP,
        );
        Get.offAllNamed('/main'); // 跳转首页
      } else {
        Get.snackbar(
          '登录失败',
          result.message ?? '请检查手机号或密码',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.redAccent,
          colorText: Colors.white,
        );
      }
    } catch (e) {
      Get.snackbar(
        '错误',
        '网络请求失败：$e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.redAccent,
        colorText: Colors.white,
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Center(
          child: Text('登录'),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                controller: _phoneController,
                decoration: const InputDecoration(label: Text('手机号')),
                keyboardType: TextInputType.phone,
                validator: (v) => v == null || v.isEmpty ? '请输入手机号' : null,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _passwordController,
                decoration: const InputDecoration(label: Text('密码')),
                obscureText: true,
                validator: (v) => v == null || v.isEmpty ? '请输入密码' : null,
              ),
              const SizedBox(height: 32),
              ElevatedButton(
                onPressed: _isLoading ? null : _login,
                child: _isLoading
                    ? const CircularProgressIndicator()
                    : const Text('登录'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
